package com.farm.sfile.utils;


import java.io.File;
import java.io.FileOutputStream; 
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.farm.parameter.FarmParameterService;
import com.farm.sfile.domain.FileBase;
import com.farm.util.validate.SSRFConnectionHandles;
import com.farm.web.WebUtils;

public class WebFiles {
	private static final String USER_AGENT = "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)";
	private static final Logger log = Logger.getLogger(WebFiles.class);

	public static boolean isLiveUrl(String url) {
		try {
			SSRFConnectionHandles.validateUrl(url);
			URL remoteUrl = new URL(url);
			HttpURLConnection uConnection = (HttpURLConnection) remoteUrl.openConnection();
			uConnection.setConnectTimeout(1000);
			uConnection.setReadTimeout(10000);
			uConnection.connect();
			if (uConnection.getResponseCode() == 404) {
				log.error(url + " http code is 404");
				return false;
			}
			return true;
		} catch (Exception e1) {
			e1 = SSRFConnectionHandles.exceptionHandle(e1);
			log.error(url + e1.getMessage());
			return false;
		}
	}

	/**
	 * 下载网络文件到本地
	 * 
	 * @param fileUrl
	 * @param localFile
	 * @return
	 * @throws IOException
	 */
	public static FileBase downloadFile(String fileUrl, FileBase fileinfo, File localFile) throws IOException {
		log.info("html img from:" + fileUrl);
		String exname = null;
		try {
			if (fileUrl.lastIndexOf("?") > 0) {
				exname = fileUrl.substring(0, fileUrl.lastIndexOf("?"));
			} else {
				exname = fileUrl;
			}
			if (fileUrl.lastIndexOf(".") > 0) {
				exname = exname.substring(exname.lastIndexOf(".") + 1);
			} else {
				exname = fileUrl;
			}
			if (exname == null || exname.length() > 10) {
				exname = "gif";
			}
		} catch (Exception e) {
			exname = "gif";
		}
		try {
			// 编码url中的中午字符
			fileUrl = encodeChinese(fileUrl, "utf-8");
		} catch (Exception e) {
			log.warn("url chinese urlencode error：" + e.getMessage());
		}

		// 返回Http的响应状态码
		InputStream input = null;
		OutputStream fos = null;
		HttpURLConnection connection = null;
		try {
			SSRFConnectionHandles.validateUrl(fileUrl);
			URL innerurl = new URL(fileUrl);
			// 创建连接的地址
			connection = (HttpURLConnection) innerurl.openConnection();
			connection.setRequestProperty("User-Agent", USER_AGENT);
			connection.setConnectTimeout(1000);
			connection.setReadTimeout(10000);
			input = connection.getInputStream();

			if (!exname.toUpperCase().equals("PNG") && !exname.toUpperCase().equals("JPG")
					&& !exname.toUpperCase().equals("JPEG") && !exname.toUpperCase().equals("GIF")) {
				exname = "jpg";
			}
			fos = new FileOutputStream(localFile);
			// 获取输入流
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = input.read(buffer, 0, 8192)) != -1) {
				fos.write(buffer, 0, bytesRead);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (input != null) {
				try {
					input.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (connection != null) {
				connection.disconnect();
			}
		}
		fileinfo.setExname(exname);
		fileinfo.setFilesize(Integer.valueOf(Long.toString(localFile.length())));
		return fileinfo;
	}

	/**
	 * 对url中的中文编码
	 * 
	 * @param url
	 * @param chartSet
	 * @return
	 */
	public static String encodeChinese(String url, String chartSet) {
		try {
			Matcher matcher = Pattern.compile("[\\u4e00-\\u9fa5]").matcher(url);
			while (matcher.find()) {
				String tmp = matcher.group();
				url = url.replaceAll(tmp, java.net.URLEncoder.encode(tmp, chartSet));
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return url;
	}

	public static void validateFile(String exname, long size) {
		String maxLength = FarmParameterService.getInstance().getParameter("config.doc.upload.length.max");
		if (size > Long.valueOf(maxLength)) {
			throw new RuntimeException("文件不能超过" + Long.valueOf(maxLength) / 1024 + "kb");
		}
		String typesstr = FarmParameterService.getInstance().getParameter("config.doc.upload.types");
		// 验证类型
		List<String> types = WebUtils.parseIds(typesstr.toUpperCase().replaceAll("，", ","));
		if (!types.contains(exname.toUpperCase())) {
			throw new RuntimeException("上传文件类型错误，允许的类型为：" + typesstr.toUpperCase().replaceAll("，", ","));
		}
	}

	public static String getExname(String fileUrl) {
		String exname = null;
		HttpURLConnection connection = null;
		try {
			URL innerurl = new URL(fileUrl);
			// 创建连接的地址
			connection = (HttpURLConnection) innerurl.openConnection();
			String filenames = connection.getHeaderField("Content-Disposition");
			if (filenames.indexOf("fileName=") >= 0) {
				exname = filenames.substring(filenames.indexOf("fileName=") + "fileName=".length());
				if (exname.lastIndexOf(".") > 0) {
					exname = exname.substring(exname.lastIndexOf(".") + 1);
				}
			} else {
				if (fileUrl.lastIndexOf("?") > 0) {
					exname = fileUrl.substring(0, fileUrl.lastIndexOf("?"));
				} else {
					exname = fileUrl;
				}
				if (fileUrl.lastIndexOf(".") > 0) {
					exname = exname.substring(exname.lastIndexOf(".") + 1);
				} else {
					exname = fileUrl;
				}
				if (exname == null || exname.length() > 10) {
					exname = "gif";
				}
			}
		} catch (Exception e) {
			exname = "gif";
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}
		return exname;
	}

	/**
	 * 获得url中的id
	 * 
	 * @param imgUrl
	 * @return
	 */
	public static String getIdbyUrl(String imgUrl) {
		String id = imgUrl.substring(imgUrl.indexOf("id=") + "id=".length());
		return id.indexOf("&") >= 0 ? id.substring(0, id.indexOf("&")) : id;
	}

}
